<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :model="formData" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="渠道名称" v-bind="validateInfos.channel">
            <a-input v-model:value="formData.channel" placeholder="请输入渠道名称" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item name="invoiceRate" label="发票点数" v-bind="validateInfos.invoiceRate">
            <a-input-number
              :style="{ width: '200px' }"
              v-model:value="formData.invoiceRate"
              step="0.01"
              max="1"
              min="0"
              :disabled="disabled"
              placeholder="请输入发票点数"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="3"><div :style="{ textAlign: 'right', marginRight: '6px' }">结算规则: </div></a-col>
        <a-col :span="19">
          <div v-for="(areaConfig, index) in formData.configs" :key="index" class="areas-div">
            <a-button danger class="delete-btn" @click="deleteConfigs(index)" :disabled="disabled">删除</a-button>
            <a-form-item
              label="保司"
              :labelCol="{ span: 6 }"
              :name="['configs', index, 'insuranceCompany']"
              :rules="{
                required: true,
                message: '选择保司',
              }"
            >
              <j-dict-select-tag v-model:value="areaConfig.insuranceCompany" dictCode="BXGS" placeholder="请选择保险公司" :disabled="disabled" />
            </a-form-item>
            <a-form-item
              :name="['configs', index, 'platform']"
              label="平台"
              :labelCol="{ span: 6 }"
              :rules="{
                required: true,
                message: '请选择平台',
              }"
            >
              <PlatformTree multiple v-model:model-value="areaConfig.platform" :disabled="disabled" />
            </a-form-item>

            <a-form-item
              :name="['configs', index, 'fixRate']"
              label="结算比例"
              :labelCol="{ span: 6 }"
              :rules="{
                required: true,
                message: '输入结算比例',
              }"
            >
              <a-input-number
                :style="{ width: '200px' }"
                v-model:value="areaConfig.fixRate"
                step="0.000001"
                max="1"
                :disabled="disabled"
                placeholder="请输入结算比例"
              />
            </a-form-item>
            <a-form-item :name="['configs', index, 'type']" label="结算其他保单" :labelCol="{ span: 6 }">
              <a-checkbox v-model:checked="areaConfig.type">结算其他保单</a-checkbox>
              <a-input-number
                v-if="areaConfig.type"
                :style="{ width: '200px' }"
                v-model:value="areaConfig.otherPolicyRate"
                step="0.000001"
                max="1"
                :disabled="disabled"
                placeholder="输入比例"
              />
            </a-form-item>
          </div>
          <a-button @click="addSettlementAreas" class="add-areas" :disabled="disabled">添加规则</a-button>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import JCategorySelect from '/@/components/Form/src/jeecg/components/JCategorySelect.vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import PlatformTree from '/@/components/BusinessComponents/PlatformTree.vue';
  import { saveOrUpdate } from '../ChannelSettlementConfig.api';
  import { Form } from 'ant-design-vue';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    channel: '',
    invoiceRate: '',
    configs: [
      {
        insuranceCompany: undefined,
        platform: undefined,
        fixRate: '',
        area: '',
        otherPolicyRate: '',
        type: false,
      },
    ],
  });

  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 3 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 14 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    channel: [{ required: true, message: '请输入渠道名称!' }],
    invoiceRate: [{ required: true, message: '请输入发票点数!' }],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

  onMounted(() => {});
  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  function addSettlementAreas() {
    if (disabled.value) return;
    formData.configs.push({
      insuranceCompany: '',
      platform: null,
      fixRate: '',
      area: '',
      otherPolicyRate: '',
      type: false,
    });
  }
  function deleteConfigs(index) {
    if (disabled.value) return;
    formData.configs.splice(index, 1);
  }

  /**
   * 新增
   */
  function add(params) {
    edit(params);
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      console.log('edit', record);
      if (!record.configs) {
        record.configs = [];
      } else {
        record.configs.forEach((item) => {
          item.type = item.type === 'OTHER' ? true : false;
        });
      }
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    console.log('submitForm', formData);

    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    const { id, channel, configs, invoiceRate } = model;
    console.log('submitForm', model);
    const configsData = configs.map((item) => {
      return {
        ...item,
        type: item.type ? 'OTHER' : 'ONE',
      };
    });
    confirmLoading.value = true;
    const params: any = {
      channel,
      invoiceRate,
      configs: configsData,
    };
    if (id) params.id = id;
    await saveOrUpdate(params, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }
  // 找到子节点的父级节点
  function findParentNode(treeData, nodeId) {
    let parentNode = null;
    let selfNode = null;
    let noParentError = '';
    treeData.forEach((item, index) => {
      if (item.key === nodeId) {
        noParentError = `请选择${item.title}下面的子节点`;
      }
      if (item.children && item.children.length > 0) {
        for (let i = 0; i < item.children.length; i++) {
          const child = item.children[i];
          if (child.key === nodeId) {
            parentNode = item;
            selfNode = child;
            break;
          }
        }
      }
    });
    return {
      parentNode,
      selfNode,
      noParentError,
    };
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
  .add-areas {
    // margin-top: 10px;
  }
  .areas-div {
    border: 1px solid #cfe5fc;
    padding: 20px;
    margin-bottom: 10px;
    position: relative;
    .delete-btn {
      position: absolute;
      top: 10px;
      right: 10px;
    }
  }
  .label {
    margin-right: 10px;
  }
  .label-right {
    margin-left: 20px;
  }
  .add-btn {
    margin-top: 10px;
  }
  .stepRatioDiv {
    padding: 20px;
    background-color: #f6f6f6;
  }
</style>
